const path = require("path");
const fs = require("fs");
const { app, BrowserWindow, ipcMain, Tray, Notification } = require("electron");

const EventHandle = require("./event");
const { event } = require("./constant");
const { Menu } = require("electron");

process.env.events = JSON.stringify(event);
process.env.toFilePath = path.resolve("C://sharpFile");
process.env.urlPath = path.resolve("c://sharpFile//temp");

// 当程序中没有文件夹时，创建文件夹
if (!fs.existsSync(path.resolve("C://sharpFile"))) {
    fs.mkdirSync(path.resolve("C://sharpFile"));
}

if (!fs.existsSync(path.resolve("c://sharpFile//temp"))) {
    fs.mkdirSync(path.resolve("c://sharpFile//temp"));
}

const electronConfig = (process.env.electronConfig &&
    JSON.parse(process.env.electronConfig || "{}")) || {
    icon: path.join(__dirname, "./logo.png"),
};
process.env.electronConfig = JSON.stringify(electronConfig);
if (!process.env.appTitle) process.env.appTitle = "图片处理程序";

console.log("main window open in readying...");
process.on("closeProcess", () => {
    console.log("receive close process command...", process.pid);
    app.quit();
});

// 开启端口的主程序
const createWindow = () => {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        fullscreen: true,
        autoHideMenuBar: true,
        icon: electronConfig.icon || null,
        webPreferences: {
            preload: path.join(__dirname, "./preload.js"),
        },
    });

    win.loadFile("./dist/index.html");
    // win.loadURL(
    //     `http://${process.env.electron_dev_host}:${process.env.electron_dev_port}`
    // );

    return win;
};

app.whenReady().then(() => {
    const title = process.env.appTitle || "图片处理程序";
    const win = createWindow();

    // 创建系统托盘
    const trayInstance = new Tray(electronConfig.icon || null);

    // notification 通知对象
    const systemMessage = new Notification({ title });

    // 注册系统托盘事件
    trayInstance.on("click", () => {
        const isMin = win.isMinimized();
        if (isMin) win.maximize();
    });
    trayInstance.setToolTip(title);
    trayInstance.setContextMenu(
        Menu.buildFromTemplate([
            {
                id: "max",
                label: "窗口最大化",
                click: () => {
                    if (!win.isMaximized()) {
                        win.maximize();
                    } else {
                        systemMessage.close();
                        systemMessage.body = "当前窗口已经是最大化！";
                        systemMessage.show();
                    }
                },
            },
            {
                id: "min",
                label: "窗口最小化",
                click: () => {
                    if (!win.isMinimized()) {
                        win.minimize();
                    } else {
                        systemMessage.close();
                        systemMessage.body = "当前窗口已经是最小化！";
                        systemMessage.show();
                    }
                },
            },
            {
                id: "clsoe",
                label: "退出程序",
                click: () => {
                    win.maximize();
                    win.webContents.send(event.EXIT_WINDOW);
                },
            },
        ])
    );

    // 注册事件
    EventHandle.listener(ipcMain, win);

    // 不可运行在 mac os的电脑系统上
    app.on("window-all-closed", () => {
        if (process.platform !== "darwin") app.quit();
    });

    // 兼容 mac os系统
    // 在 macOS 系统内, 如果没有已开启的应用窗口， 击托盘图标时通常会重新创建一个新窗口
    app.on("activate", () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});
